package com.logos.cartoon.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.logos.cartoon.entity.User;
import com.logos.cartoon.enums.IsDeleteFlagEnum;
import com.logos.cartoon.service.UserService;
import com.logos.cartoon.mapper.UserMapper;
import com.logos.cartoon.utils.Md5Utils;
import org.springframework.stereotype.Service;

/**
 * @author rose
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-05-23 22:34:06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {


    @Override
    public Boolean login(String username, String password) {
        // 对密码进行加密
        String encryptedPassword = Md5Utils.encode(password);
        // 根据用户名和密码查询用户
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", username);
        User user = this.getOne(wrapper);
        // 当前用户不存在
        if (user == null) {
            return false;
        }
        wrapper.eq("password_hash", encryptedPassword);
        user = this.getOne(wrapper);
        if (user == null) {
            // 密码错误
            return false;
        }
        return true;
    }

    @Override
    public Boolean register(String username, String password) {
        // 查询该用户名是否被使用过
        QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", username);
        User user = this.getOne(wrapper);
        if (user != null) {
            // 用户名已被使用
            return false;
        }
        user = new User();
        user.setUsername(username);
        user.setPasswordHash(Md5Utils.encode(password));
        user.setAuthKey(Md5Utils.encode(String.valueOf(System.currentTimeMillis())));
        user.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        return this.save(user);
    }
}




